﻿using System;
using System.Data;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace whu2020302051098 {
    public partial class AttributeTable : Form {

        private ILayer pLayer; //需要打开属性表的图层
        private IFeatureLayer pFeatureLayer;
        private IFeatureClass pFeatureClass;
        private ILayerFields pLayerFields;

        public AttributeTable(ILayer pLyr) {
            InitializeComponent();
            pLayer = pLyr;
        }


        private string getValidFeatureClassName(string FCname) {
            int dot = FCname.IndexOf(".");
            if (dot != -1) {
                return FCname.Replace(".", "_");
            }
            return FCname;
        }

        private void AttributeTable_Load(object sender, EventArgs e) {
            try {
                string tableName;
                tableName = getValidFeatureClassName(pLayer.Name); //从图层名中获取名称，这个类在后面有定义，用于获取一个有效的名称
                this.Text = tableName + "属性表"; //替换窗体名称，“属性表”.ToString()其作用是将其它类型以字符串类型表示
                pFeatureLayer = pLayer as IFeatureLayer;
                pFeatureClass = pFeatureLayer.FeatureClass;
                pLayerFields = pFeatureLayer as ILayerFields; //as运算符用于执行引用类型的显式类型转换。 如果要转换的类型与指定类型兼容，转换就会成功；如果类型不兼容，则返回null。
                DataTable dt = new DataTable(pFeatureLayer.Name); //实例化数据表,表的名称是pFeatureLayer.Name
                DataColumn dc = null;
                for (int i = 0; i < pLayerFields.FieldCount; i++) {
                    //通过实例化获取数据表的字段名
                    dc = new DataColumn(pLayerFields.get_Field(i).Name);
                    dt.Columns.Add(dc); //在数据表得到列
                    dc = null;
                }
                IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false); IFeature pFeature = pFeatureCursor.NextFeature();
                while (pFeature != null) {
                    DataRow dr = dt.NewRow(); //dr 即为新添加的行，每行数据是由多列构成的，如果在 DataTable 对象中已经存在表结构，则直接使用”dr[ 编号或列名 ]= 值”的形式即可为表中的列赋值。
                    for (int j = 0; j < pLayerFields.FieldCount; j++) {
                        // 在pLayerFields对象中找到pFeatureClass.ShapeFieldName的索引(就是第几列)，并在数据表中显示该shape的类型。                      
                        if (pLayerFields.FindField(pFeatureClass.ShapeFieldName) == j) {
                            dr[j] = pFeatureClass.ShapeType.ToString(); // pFeatureClass.ShapeType得到形状类型值，然后转换为字符串。若没有该句就无法显示形状类型，效果见下页,现在看看。
                        }
                        else {
                            dr[j] = pFeature.get_Value(j); //直接返回这个值
                        }
                    }
                    dt.Rows.Add(dr);
                    pFeature = pFeatureCursor.NextFeature();//游标下移
                }
                dataGridView1.DataSource = dt;
            }
            catch (Exception exc) {
                MessageBox.Show("读取属性表失败：" + exc.Message);
                this.Dispose();
            }
        }
    }
}
